/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.sbhotel.chotellauncher;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.sbhotel.chotellauncher.activity.ADActivity;
import com.sbhotel.chotellauncher.activity.NoFunctionActivity;
import com.sbhotel.chotellauncher.activity.SettingsActivity;
import com.sbhotel.chotellauncher.activity.WarningTVActivity;
import com.sbhotel.chotellauncher.adapter.HomeBottomMenuAdapter;
import com.sbhotel.chotellauncher.adapter.MyRecyclerAdapter;
import com.sbhotel.chotellauncher.callback.HttpCallBackListener;
import com.sbhotel.chotellauncher.callback.PingCallbackListener;
import com.sbhotel.chotellauncher.constant.Constants;
import com.sbhotel.chotellauncher.entity.AppBean;
import com.sbhotel.chotellauncher.entity.BaseResponseBean;
import com.sbhotel.chotellauncher.entity.GroupInfoBean;
import com.sbhotel.chotellauncher.entity.HotelInfo;
import com.sbhotel.chotellauncher.entity.LauncherMainMenuBean;
import com.sbhotel.chotellauncher.util.DateUtil;
import com.sbhotel.chotellauncher.util.HttpUtil;
import com.sbhotel.chotellauncher.util.LauncherConfigUtil;
import com.sbhotel.chotellauncher.util.SPUtil;
import com.sbhotel.chotellauncher.util.Utils;
import com.sbhotel.chotellauncher.widget.HorizontalRecyclerView;

import java.util.Date;

/*
 * MainActivity class that loads {@link MainFragment}.
 */
public class MainActivity extends Activity implements ViewTreeObserver.OnGlobalFocusChangeListener,
        MyRecyclerAdapter.OnItemClickLitener, HomeBottomMenuAdapter.OnBottomMenuItemClickLitener, PingCallbackListener{

    private HorizontalRecyclerView main_horizontalRecyclerView;
    private HorizontalRecyclerView bottom_horizontalRecyclerView;

    MyRecyclerAdapter menuAdaper;
    HomeBottomMenuAdapter bottomMenuAdapter;
    TextView tvDateTime, tvUserName, tvHotelName;
    ImageView wifi, msg;
    //设置网络按钮
    View connectWifi;

    View mainLayout, lockLayout, netErrorLayout;

    // 显示广告
    private Handler mHandler01 = new Handler();
    private Handler mHandler02 = new Handler();

    /* 上一次User有动作的Time Stamp */
    private Date lastUpdateTime;
    /* 计算User有几秒没有动作的 */
    private long timePeriod;

    /* 静止超过N秒将自动进入屏保 单位（s 秒）*/
    private float mHoldStillTime = 300;
    /*标识当前是否进入了屏保*/
    private boolean isRunScreenSaver;

    /*时间间隔*/
    private long intervalScreenSaver = 1000;
    private long intervalKeypadeSaver = 1000;

    //当前心跳时长（秒）
    private int currentIntervalHeart = 0;
    //心跳周期
    private final int intervalHeart = 30 * 60;

    private boolean checkVersionFlag = false;

    //hotel logo
    ImageView ivHotelLogo;
    //Gson
    Gson mGson = new Gson();

    StaggeredGridLayoutManager layoutManager1;
    StaggeredGridLayoutManager layoutManager2;

    MyAsyncTask asyncTask;
    //当前焦点view
    View currentFocusView = main_horizontalRecyclerView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        asyncTask = new MyAsyncTask();
        initView();
        initData();
        Log.d(Constants.LOG_TAG, "MainActivity onCreate");
    }

    public void initView() {
        registerBroadcast();
        /////////////////////
        menuAdaper = new MyRecyclerAdapter(this, null);
        layoutManager1 = new StaggeredGridLayoutManager(1, OrientationHelper.HORIZONTAL);
        main_horizontalRecyclerView = (HorizontalRecyclerView) findViewById(R.id.horizontalRecyclerView);
        main_horizontalRecyclerView.setLayoutManager(layoutManager1);

        main_horizontalRecyclerView.setAdapter(menuAdaper);
        menuAdaper.setOnItemClickLitener(this);

        setHeaderView(main_horizontalRecyclerView);
        setFooterView(main_horizontalRecyclerView);


        //// bottom menu
        bottomMenuAdapter = new HomeBottomMenuAdapter(this);
        layoutManager2 = new StaggeredGridLayoutManager(1, OrientationHelper.HORIZONTAL);
        bottom_horizontalRecyclerView = findViewById(R.id.bottom_h_recyclerView);
        bottom_horizontalRecyclerView.setLayoutManager(layoutManager2);
        bottom_horizontalRecyclerView.setAdapter(bottomMenuAdapter);
        bottomMenuAdapter.setOnItemClickLitener(this);

        mainLayout = findViewById(R.id.layout_main);
        lockLayout = findViewById(R.id.layout_lock);
        netErrorLayout = findViewById(R.id.layout_net_error);

        /////////////
        tvUserName = findViewById(R.id.user_name);
        tvDateTime = findViewById(R.id.tv_date);
        ivHotelLogo = findViewById(R.id.iv_hotel_logo);
        tvHotelName = findViewById(R.id.tv_hotel_name);

        tvDateTime.setText(DateUtil.parseDateToStr(new Date(), DateUtil.DATE_FORMAT_HHMM));
        handler.sendEmptyMessageDelayed(0, 5000);//update time
        handler.sendEmptyMessageDelayed(2, 2000);//refresh focus
        handler.sendEmptyMessageDelayed(3, 5 * 60000);//ping network

        ///////初始化状态栏wifi图标
        wifi = findViewById(R.id.iv_wifi);
        wifi.setImageResource(R.mipmap.wifi_network_error);

        //
        connectWifi = findViewById(R.id.tv_connect_wifi);
        connectWifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(Constants.LOG_TAG, "connect wifi click");
                Intent wifiIntent = new Intent();
                wifiIntent.setComponent(new ComponentName("com.sbhotel.netwarn", "com.sbhotel.netwarn.activity.WifiConnectActivity"));
                startActivity(wifiIntent);
            }
        });

        msg = findViewById(R.id.iv_msg);
        msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, NoFunctionActivity.class);
                intent.putExtra("title", "通知中心");
                startActivity(intent);
                HttpUtil.dataReport(Constants.CODE_MSG_BUTTON, Utils.getDeviceUn(MainActivity.this));
            }
        });
        msg.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                currentFocusView = msg;
            }
        });

        /* 初始取得User可触碰屏幕的时间 */
        lastUpdateTime = new Date(System.currentTimeMillis());

        initUI();
    }

    private void initData() {
        String hotelName = (String) SPUtil.get(MainActivity.this, Constants.SP_KEY_HOTEL_NAME, "");
        String hotelLogo = (String) SPUtil.get(MainActivity.this, Constants.SP_KEY_HOTEL_LOGO, "");
        if (!TextUtils.isEmpty(hotelName)) {
            tvHotelName.setText(hotelName);
        }
        if (!TextUtils.isEmpty(hotelLogo)) {
            Glide.with(MainActivity.this).load(hotelLogo)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop())
                            .placeholder(R.mipmap.hotel_logo)
                            .error(R.mipmap.hotel_logo))
                    .into(ivHotelLogo);
        }
        //MyApplication.netWorkErrorDialog = new NetWorkErrorDialog(this);
    }

    private void showMainLayout() {
        Log.d(Constants.LOG_TAG, "showMainLayout");
        mainLayout.setVisibility(View.VISIBLE);
        lockLayout.setVisibility(View.GONE);
        netErrorLayout.setVisibility(View.GONE);
        main_horizontalRecyclerView.requestFocus();
    }

    private void showLockLayout() {
        Log.d(Constants.LOG_TAG, "showLockLayout");
        mainLayout.setVisibility(View.GONE);
        lockLayout.setVisibility(View.VISIBLE);
        netErrorLayout.setVisibility(View.GONE);
    }

    private void showNetErrorLayout() {
        Log.d(Constants.LOG_TAG, "showNetErrorLayout");
        mainLayout.setVisibility(View.GONE);
        lockLayout.setVisibility(View.GONE);
        netErrorLayout.setVisibility(View.VISIBLE);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0: //更新时间  发送心跳包
                    //Log.d("showboom", "time = " + DateUtil.parseDateToStr(new Date(), DateUtil.DATE_FORMAT_HHMM));
                    currentIntervalHeart++;
                    String time = DateUtil.parseDateToStr(new Date(), DateUtil.DATE_FORMAT_HHMM);
                    tvDateTime.setText(time);
                    updateGreetings(time.substring(0, 2));
                    //Log.d("showboom", "currentIntervalHeart = " + currentIntervalHeart);
                    if (currentIntervalHeart > intervalHeart) {
                        currentIntervalHeart = 0;
                        HttpUtil.sendHeart(Utils.getDeviceUn(MainActivity.this));
                    }
                    sendEmptyMessageDelayed(0, 1000);
                    break;
                case 1:
                    //sendEmptyMessageDelayed(1, 60000);
                    break;
                case 2: //main_horizontalRecyclerView get focus
                    main_horizontalRecyclerView.requestFocus();
                    break;
                case 3:  // 5分钟ping一次网
                    Utils.doPingAsync(MainActivity.this);
                    sendEmptyMessageDelayed(3, 5 * 60 * 1000);
                    break;
                case 4:
                    // 更新主菜单 和 底部菜单数据
                    LauncherMainMenuBean bean = (LauncherMainMenuBean) msg.obj;
                    menuAdaper.setDataList(bean.getData().getCont_list());
                    bottomMenuAdapter.setDataList(bean.getData().getService_list());
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onPingFinish(final boolean result) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (result) {
                    SPUtil.put(MainActivity.this, Constants.SP_KEY_NET_ERROR, false);
                    wifi.setImageResource(R.mipmap.wifi_network);
                } else {
                    SPUtil.put(MainActivity.this, Constants.SP_KEY_NET_ERROR, true);
                    wifi.setImageResource(R.mipmap.wifi_network_error);
                }
            }
        });
    }

    private void checkVersion(String device_un) {
        Intent intent = new Intent();
        ComponentName componentName = new ComponentName("com.sbhotel.upgrade", "com.sbhotel.upgrade.service.VersionCheckService");
        intent.putExtra("device_un", device_un);
        intent.putExtra("app_version", Utils.getVerName(this));
        //Log.d(Constants.LOG_TAG, "device_un=" + device_un + " app_version = " + Utils.getVerName(this));
        intent.setComponent(componentName);
        startService(intent);
    }

    private void getHotelInfo() {
        HttpUtil.getHotelInfo(MainActivity.this, new HttpCallBackListener() {
            @Override
            public void onFinish(final String response) {
                Log.d(Constants.LOG_TAG, "getHotelInfo response = " + response);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        HotelInfo hotelInfo = mGson.fromJson(response, HotelInfo.class);
                        if (hotelInfo != null) {
                            if (hotelInfo.getCode() == 0) {
                                Glide.with(MainActivity.this).load(hotelInfo.getData().getLogo_img())
                                        .apply(RequestOptions.bitmapTransform(new CircleCrop())
                                                .placeholder(R.mipmap.hotel_logo)
                                                .error(R.mipmap.hotel_logo))
                                        .into(ivHotelLogo);
                                tvHotelName.setText(" · " + hotelInfo.getData().getHotel_name());
                                String hotelName = hotelInfo.getData().getHotel_name();
                                String logoUrl = hotelInfo.getData().getLogo_img();
                                String device_un = hotelInfo.getData().getDevice_info().getDevice_un();
                                if (!TextUtils.isEmpty(hotelName) && !TextUtils.isEmpty(logoUrl) && !TextUtils.isEmpty(device_un)) {
                                    SPUtil.put(MainActivity.this, Constants.SP_KEY_HOTEL_NAME, hotelInfo.getData().getHotel_name());
                                    SPUtil.put(MainActivity.this, Constants.SP_KEY_HOTEL_LOGO, hotelInfo.getData().getLogo_img());
                                    SPUtil.put(MainActivity.this, Constants.SP_KEY_DEVICE_UN_CODE, hotelInfo.getData().getDevice_info().getDevice_un());
                                    //SPUtil.put(MainActivity.this, Constants.SP_KEY_UN_MARK, hotelInfo.getData().getUni_mark());
                                    getLauncherData();
                                }
                                int useState = hotelInfo.getData().getDevice_info().getUse_status();
                                if (useState == 0) {
                                    showLockLayout();
                                    SPUtil.put(MainActivity.this, Constants.SP_KEY_IS_LOCK, true);
                                } else {
                                    showMainLayout();
                                    SPUtil.put(MainActivity.this, Constants.SP_KEY_IS_LOCK, false);
                                }
                                if (!checkVersionFlag) {
                                    checkVersionFlag = true;
                                    checkVersion(hotelInfo.getData().getDevice_info().getDevice_un());
                                }
                            } else {
                                Log.d(Constants.LOG_TAG, "getHotelInfo errorCode=" + hotelInfo.getCode());
                                Log.d(Constants.LOG_TAG, "getHotelInfo errorMsg=" + hotelInfo.getMessage());
                            }
                        }
                    }
                });

            }

            @Override
            public void onError(Exception e) {
                Log.d(Constants.LOG_TAG, "getHotelInfo error:" + e.getMessage());
                e.printStackTrace();
            }
        });
    }

    //获取酒店信息
    class MyAsyncTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            String param = "service=identifyDevice&version=" + Constants.INTEREFACT_VERSION
                    + "&pro=" + Constants.PRO + "&device_model=" + Constants.DEVICE_MODEL
                    + "&device_sn=" + Utils.getDeviceSN()
                    + "&device_mac" + Utils.getMac2();
            return HttpUtil.doPost(Constants.MAIN_URL, param);
        }

        @Override
        protected void onPostExecute(String s) {
            BaseResponseBean bean = new Gson().fromJson(s, BaseResponseBean.class);
            if(bean != null && bean.getCode() == 0) {
                String deviceUn = bean.getData().getDevice_un();
                if(!TextUtils.isEmpty(deviceUn)) {
                    SPUtil.put(MainActivity.this, Constants.SP_KEY_DEVICE_UN_CODE , deviceUn);
                    getHotelInfo();
                }
            }
        }
    }

    private void getLauncherData() {
        String deviceUn = (String) SPUtil.get(this, Constants.SP_KEY_DEVICE_UN_CODE, "");
        if (TextUtils.isEmpty(deviceUn)) return;
        String param = "&device_un=" + deviceUn
                + "&service=getLauncherConfig&version=" + Constants.INTEREFACT_VERSION;
        HttpUtil.doPostAsyn(Constants.MAIN_URL, param, new HttpCallBackListener() {
            @Override
            public void onFinish(String response) {
                Log.d(Constants.LOG_TAG, "getLauncherData response = " + response);
                LauncherMainMenuBean bean = mGson.fromJson(response, LauncherMainMenuBean.class);
                if (bean != null && bean.getCode() == 0) {
                    /*Message msg = Message.obtain();
                    msg.obj = bean;
                    msg.what = 4; // 更新主菜单 和 底部菜单数据
                    handler.sendMessage(msg);*/

                    String currentVersion = (String) SPUtil.get(MainActivity.this, Constants.SP_KEY_CURRENT_CONF_VERSION, "");
                    Log.d(Constants.LOG_TAG, "currentVersion = " + currentVersion);
                    if (TextUtils.isEmpty(currentVersion) || !currentVersion.equals(bean.getData().getConf_version())) {
                        //将获取到的launcher数据 存储到文件config中
                        LauncherConfigUtil.writeFileData(MainActivity.this, Constants.CONFIG_FILE_PATH, response);
                        //创建下载任务
                        LauncherConfigUtil.createDownloadTask(MainActivity.this, response);
                    }
                } else {
                    Log.d(Constants.LOG_TAG, "get launcher data error= " + response);
                }
            }

            @Override
            public void onError(Exception e) {
                Log.d(Constants.LOG_TAG, "get launcher data error:" + e.getMessage());
                e.printStackTrace();
            }
        });
    }

    //通过包名启动app
    private void startAppViaPkg(String packageName, int position) {
        PackageManager packageManager = getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage(packageName);
        if (intent == null) {
            Intent notSupportIntent = new Intent(this, NoFunctionActivity.class);
            switch (position) {
                case 2:
                    notSupportIntent.putExtra("title", "中影院线");
                    startActivity(notSupportIntent);
                    break;
                default:
                    Toast.makeText(this, "应用未安装", Toast.LENGTH_LONG).show();
                    break;
            }
            //Toast.makeText(this, "应用未安装", Toast.LENGTH_LONG).show();
        } else {
            intent.setPackage(null);
            startActivity(intent);
        }
    }

    @Override
    public void onGlobalFocusChanged(View oldFocus, View newFocus) {

    }

    //注册接收器
    private void registerBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);
    }

    private void unRegisterBroadcast() {
        unregisterReceiver(receiver);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == WifiManager.WIFI_STATE_CHANGED_ACTION) {
                switch (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)) {
                    case WifiManager.WIFI_STATE_DISABLED: {
                        wifi.setImageResource(R.mipmap.wifi_network_error);
                        SPUtil.put(context, Constants.SP_KEY_NET_ERROR, true);
                        Log.d(Constants.LOG_TAG, "MainActivity WIFI_STATE_DISABLED put netError true");
                        showNetErrorLayout();
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLED: {
                        if (asyncTask.getStatus() != AsyncTask.Status.RUNNING && asyncTask.getStatus() != AsyncTask.Status.FINISHED) {
                            asyncTask.execute();
                        }
                        SPUtil.put(context, Constants.SP_KEY_NET_ERROR, false);
                        wifi.setImageResource(R.mipmap.wifi_network);
                        boolean isLock = (boolean) SPUtil.get(context, Constants.SP_KEY_IS_LOCK, false);
                        if (isLock) {
                            showLockLayout();
                        } else {
                            showMainLayout();
                        }

                        break;
                    }
                    case WifiManager.WIFI_STATE_UNKNOWN: {
                        SPUtil.put(context, Constants.SP_KEY_NET_ERROR, true);
                        Log.d(Constants.LOG_TAG, "MainActivity WIFI_STATE_DISABLED put netError true");
                        wifi.setImageResource(R.mipmap.wifi_network_error);
                        showNetErrorLayout();
                        break;
                    }
                }
            }

            // 监听网络连接，包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                //获取联网状态的NetworkInfo对象
                //ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                //NetworkInfo info = connectivityManager.getActiveNetworkInfo();
                if (info != null) {
                    //如果当前的网络连接成功并且网络连接可用
                    if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {

                        if (asyncTask.getStatus() != AsyncTask.Status.RUNNING && asyncTask.getStatus() != AsyncTask.Status.FINISHED) {
                            asyncTask.execute();
                        }
                        wifi.setImageResource(R.mipmap.wifi_network);
                        SPUtil.put(context, Constants.SP_KEY_NET_ERROR, false);
                        boolean isLock = (boolean) SPUtil.get(context, Constants.SP_KEY_IS_LOCK, false);
                        if (isLock) {
                            showLockLayout();
                        } else {
                            showMainLayout();
                        }

                    } else {
                        SPUtil.put(context, Constants.SP_KEY_NET_ERROR, true);
                        //Log.d(Constants.LOG_TAG, "MainActivity CONNECTIVITY_ACTION put netError true");
                        wifi.setImageResource(R.mipmap.wifi_network_error);
                        showNetErrorLayout();
                    }
                }
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (Constants.CONTROLER.equals("500")) return true;
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_CENTER:
                //Toast.makeText(MainActivity.this, "点击了OK", Toast.LENGTH_SHORT).show();
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (layoutManager2.findViewByPosition(0).hasFocus()) {
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                if (msg.hasFocus()) {
                    return true;
                }
                if (layoutManager2.findViewByPosition(Constants.initHomeBottomMenuData().size() - 1).hasFocus()) {
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_DPAD_UP:

                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(main_horizontalRecyclerView.hasFocus()) {
            currentFocusView = main_horizontalRecyclerView;
        } else if(bottom_horizontalRecyclerView.hasFocus()) {
            currentFocusView = bottom_horizontalRecyclerView;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onItemClick(View view, Object data, int position) {
        String reportId = "";
        if (data == null) {
            switch (position) {
                case 0:
                    startActivity(new Intent(MainActivity.this, WarningTVActivity.class));
                    reportId = Constants.CODE_MAIN_MENU_1;
                    break;
                case 1:
                    //银河奇异果
                    startAppViaPkg("com.gitvdemo.video", position);
                    reportId = Constants.CODE_MAIN_MENU_2;
                    break;
                case 2:
                    //中影院线
                    startAppViaPkg("com.txxxv", position);
                    reportId = Constants.CODE_MAIN_MENU_3;
                    break;
                case 3:
                    //短视频
                    startAppViaPkg("com.ixigua.android.tv.wasu", position);
                    reportId = Constants.CODE_MAIN_MENU_4;
                    break;
                case 4:
                    //儿童频道
                    startAppViaPkg("com.slanissue.tv.erge", position);
                    reportId = Constants.CODE_MAIN_MENU_5;
                    break;
                case 5:
                    //购物
                    startAppViaPkg("com.ocj.tv", position);
                    reportId = Constants.CODE_MAIN_MENU_6;
                    break;
                case 6:
                    //电竞
                    startAppViaPkg("cn.jj.tv", position);
                    reportId = Constants.CODE_MAIN_MENU_7;
                    break;
                case 7:
                    //旅游
                    startAppViaPkg("com.qunar.travelplan.tv", position);
                    reportId = Constants.CODE_MAIN_MENU_8;
                    break;
                default:
                    reportId = "";
                    break;
            }

        } else {
            LauncherMainMenuBean.DataBean.ContListBean bean = (LauncherMainMenuBean.DataBean.ContListBean) data;
            String pkgName = bean.getApp_package_name();
            String clsName = bean.getApp_package_classname();
            switch (position) {
                case 0:
                    reportId = Constants.CODE_MAIN_MENU_1;
                    break;
                case 1:
                    reportId = Constants.CODE_MAIN_MENU_2;
                    break;
                case 2:
                    reportId = Constants.CODE_MAIN_MENU_3;
                    break;
                case 3:
                    reportId = Constants.CODE_MAIN_MENU_4;
                    break;
                case 4:
                    reportId = Constants.CODE_MAIN_MENU_5;
                    break;
                case 5:
                    reportId = Constants.CODE_MAIN_MENU_6;
                    break;
                case 6:
                    reportId = Constants.CODE_MAIN_MENU_7;
                    break;
                case 7:
                    reportId = Constants.CODE_MAIN_MENU_8;
                    break;
            }
            if (TextUtils.isEmpty(clsName)) {
                startAppViaPkg(pkgName, position);
            } else {
                startActivity(new Intent().setComponent(new ComponentName(pkgName, clsName)));
            }
        }
        currentFocusView = main_horizontalRecyclerView;
        HttpUtil.dataReport(reportId, Utils.getDeviceUn(MainActivity.this));
    }

    @Override
    public void onBackPressed() {
    }

    @Override
    protected void onDestroy() {
        unRegisterBroadcast();
        Log.d(Constants.LOG_TAG, "MainActivity onDestroy");
        super.onDestroy();
    }

    /**
     * 底部菜单点击事件
     *
     * @param view
     * @param data
     * @param position
     */
    @Override
    public void onBottomMenuItemClick(View view, Object data, int position) {
        Intent intent;
        String reportId = "";
        if (data instanceof AppBean) {
            switch (position) {
                case 0:
                    //startActivity(new Intent(MainActivity.this, NoFunctionActivity.class));
                    intent = new Intent(MainActivity.this, NoFunctionActivity.class);
                    intent.putExtra("title", "智能健康");
                    startActivity(intent);
                    reportId = Constants.CODE_MAIN_BOTTOM_MENU_1;
                    break;
                case 1:
                    intent = new Intent(MainActivity.this, NoFunctionActivity.class);
                    intent.putExtra("title", "智能控制");
                    startActivity(intent);
                    reportId = Constants.CODE_MAIN_BOTTOM_MENU_2;
                    break;
                case 2:
                    //startActivity(new Intent(MainActivity.this, ServiceActivity.class));
                    intent = new Intent(MainActivity.this, NoFunctionActivity.class);
                    intent.putExtra("title", "客房服务");
                    startActivity(intent);
                    reportId = Constants.CODE_MAIN_BOTTOM_MENU_3;
                    break;
                case 3:
                    intent = new Intent(MainActivity.this, NoFunctionActivity.class);
                    intent.putExtra("title", "快速退房");
                    startActivity(intent);
                    reportId = Constants.CODE_MAIN_BOTTOM_MENU_4;
                    //Toast.makeText(MainActivity.this, "服务即将上线，敬请期待...", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    startActivity(new Intent(MainActivity.this, SettingsActivity.class));
                    reportId = Constants.CODE_MAIN_BOTTOM_MENU_5;
                    break;
                case 5:
                    //startAppViaPkg("com.hpplay.happyplay.aw");
                    intent = new Intent(MainActivity.this, NoFunctionActivity.class);
                    intent.putExtra("title", "多屏互动");
                    startActivity(intent);
                    reportId = Constants.CODE_MAIN_BOTTOM_MENU_6;
                    break;
                default:
                    break;
            }
        } else if (data != null && data instanceof LauncherMainMenuBean.DataBean.ServiceListBean) {
            LauncherMainMenuBean.DataBean.ServiceListBean bean = (LauncherMainMenuBean.DataBean.ServiceListBean) data;
            String pkgName = bean.getApp_package_name();
            String clsName = bean.getApp_package_classname();
            String cotentName = "";
            switch (position) {
                case 0:
                    reportId = Constants.CODE_MAIN_BOTTOM_MENU_1;
                    break;
                case 1:
                    reportId = Constants.CODE_MAIN_BOTTOM_MENU_2;
                    break;
                case 2:
                    reportId = Constants.CODE_MAIN_BOTTOM_MENU_3;
                    break;
                case 3:
                    reportId = Constants.CODE_MAIN_BOTTOM_MENU_4;
                    break;
                case 4:
                    reportId = Constants.CODE_MAIN_BOTTOM_MENU_5;
                    break;
                case 5:
                    reportId = Constants.CODE_MAIN_BOTTOM_MENU_6;
                    break;
                default:
                    break;
            }
            if (TextUtils.isEmpty(clsName) && TextUtils.isEmpty(pkgName)) {
                //Log.d(Constants.LOG_TAG, "pkgName and clsName are null.");
                intent = new Intent(MainActivity.this, NoFunctionActivity.class);
                intent.putExtra("title", bean.getService_name());
                startActivity(intent);
            } else if (!TextUtils.isEmpty(clsName) && !TextUtils.isEmpty(pkgName)) {
                startActivity(new Intent().setComponent(new ComponentName(pkgName, clsName)));
            } else {
                startAppViaPkg(pkgName, position);
            }
        }
        currentFocusView = bottom_horizontalRecyclerView;
        HttpUtil.dataReport(reportId, Utils.getDeviceUn(MainActivity.this));
    }

    /**
     * 计时线程
     */
    private Runnable mTask01 = new Runnable() {

        @Override
        public void run() {
            Date timeNow = new Date(System.currentTimeMillis());
            SystemClock.uptimeMillis();
            /* 计算User静止不动作的时间间距 */
            /**当前的系统时间 - 上次触摸屏幕的时间 = 静止不动的时间**/
            timePeriod = (long) timeNow.getTime() - (long) lastUpdateTime.getTime();
            /*将静止时间毫秒换算成秒*/
            float timePeriodSecond = ((float) timePeriod / 1000);

            if (timePeriodSecond > 400) {
                updateUserActionTime();
            }
            if (timePeriodSecond > mHoldStillTime && timePeriodSecond < 400) {
                if (isRunScreenSaver == false) {  //说明没有进入屏保
                    /* 启动线程去显示屏保 */
                    mHandler02.postAtTime(mTask02, intervalScreenSaver);
                    /*显示屏保置为true*/
                    isRunScreenSaver = true;
                } else {
                    /*屏保正在显示中*/
                }
            } else {
                /*说明静止之间没有超过规定时长*/
                isRunScreenSaver = false;
            }
            /*反复调用自己进行检查*/
            mHandler01.postDelayed(mTask01, intervalKeypadeSaver);
        }
    };

    /**
     * 持续屏保显示线程
     */
    private Runnable mTask02 = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (isRunScreenSaver == true) {  //如果屏保正在显示，就计算不断持续显示
//				hideOriginalLayout();
                showScreenSaver();
                mHandler02.postDelayed(mTask02, intervalScreenSaver);
            } else {
                mHandler02.removeCallbacks(mTask02);  //如果屏保没有显示则移除线程
            }
        }
    };

    /**
     * 显示屏保
     */
    private void showScreenSaver() {
        Intent intent = new Intent(this, ADActivity.class);
        startActivity(intent);

    }

    /*用户有操作的时候不断重置静止时间和上次操作的时间*/
    private void updateUserActionTime() {
        Date timeNow = new Date(System.currentTimeMillis());
        timePeriod = timeNow.getTime() - lastUpdateTime.getTime();
        lastUpdateTime.setTime(timeNow.getTime());
    }

    @Override
    protected void onResume() {
        super.onResume();
        /*activity显示的时候启动线程*/
        mHandler01.postAtTime(mTask01, intervalKeypadeSaver);
        Log.d(Constants.LOG_TAG, "MainActivity onResume");
        boolean netError = (boolean) SPUtil.get(this, Constants.SP_KEY_NET_ERROR, false);
        if (netError) {
            showNetErrorLayout();
        } else {
            boolean isLock = (boolean) SPUtil.get(this, Constants.SP_KEY_IS_LOCK, false);
            //checkDeviceIsLock(isLock);
            if (isLock) {
                showLockLayout();
            } else {
                showMainLayout();
            }
        }
        if(currentFocusView != null) {
            currentFocusView.requestFocus();
        }
    }

    @Override
    protected void onPause() {
        /*activity不可见的时候取消线程*/
        mHandler01.removeCallbacks(mTask01);
        mHandler02.removeCallbacks(mTask02);
        Log.d(Constants.LOG_TAG, "MainActivity onPause");
        super.onPause();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        updateUserActionTime();
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onRestart() {
        updateUserActionTime();
        Log.d(Constants.LOG_TAG, "MainActivity onRestart");
        super.onRestart();
    }


    int currentHour = -1;

    private void updateGreetings(String hour) {
        int time = Integer.parseInt(hour);
        if (currentHour == time) {
            return;
        } else {
            currentHour = time;
        }
        if (currentHour == -1) {
            currentHour = time;
        }
        if (time >= 3 && time <= 5) {
            tvUserName.setText("凌晨好");
        } else if (time == 6 || time == 7) {
            tvUserName.setText("早晨好");
        } else if (time >= 8 && time <= 10) {
            tvUserName.setText("上午好");
        } else if (time == 11 || time == 12) {
            tvUserName.setText("中午好");
        } else if (time >= 13 && time <= 16) {
            tvUserName.setText("下午好");
        } else if (time == 17 || time == 18) {
            tvUserName.setText("傍晚好");
        } else if (time >= 19 && time <= 22) {
            tvUserName.setText("晚上好");
        } else if (time == 23 || time >= 0 && time <= 2) {
            tvUserName.setText("深夜好");
        }
    }

    private void setHeaderView(RecyclerView view) {
        View header = LayoutInflater.from(this).inflate(R.layout.header, view, false);
        menuAdaper.setHeaderView(header);
    }

    private void setFooterView(RecyclerView view) {
        View footer = LayoutInflater.from(this).inflate(R.layout.footer, view, false);
        menuAdaper.setFooterView(footer);
    }

    private void initUI() {
        Log.d(Constants.LOG_TAG, "init UI start!");
        String config = LauncherConfigUtil.readFileData(this, Constants.CONFIG_FILE_OK_PATH);
        //String configVersion = (String) SPUtil.get(this, Constants.SP_KEY_CURRENT_CONF_VERSION, null);
        if (!TextUtils.isEmpty(config)) {
            if (LauncherConfigUtil.checkConfigFile(this, config)) {
                LauncherMainMenuBean bean = mGson.fromJson(config, LauncherMainMenuBean.class);
                //如果版本号不一致， 加载配置文件 并保存为当前版本号
                //if(!bean.getData().getConf_version().equals(configVersion)) {
                menuAdaper.setDataList(bean.getData().getCont_list());
                bottomMenuAdapter.setDataList(bean.getData().getService_list());
                //}
            } else {
                Log.d(Constants.LOG_TAG, "config file xxxxxxxxxx");
            }
        }
        Log.d(Constants.LOG_TAG, "init UI end!");
    }



}
